package com.neusoft.tools;

import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在此工具类中实现了两个方法，用于实现对地址的初始化，其中地址数据存储在“src/resource/data/ProvinceDB”
 */
public class AddressMapUtils {
    /**
     * 从数据库中读取省市的数据
     * @return 一个HashMap其中key为省份名的字符串，value为一个存储着对应省份下市区的列表
     */
    public static Map<String, List<String>> initAddressMap() throws IOException {
        Map<String, List<String>> addressMap = new HashMap<>();

        String resourcePath = "resource/data/ProvinceDB.txt";

        InputStream inputStream = AddressMapUtils.class.getClassLoader().getResourceAsStream(resourcePath);

        if (inputStream == null) {
            throw new IOException("无法在 classpath 中找到资源文件: " + resourcePath);
        }
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] parts = line.split("：");
                if (parts.length == 2) {
                    String province = parts[0];
                    String[] cityArray = parts[1].split("、");
                    List<String> cityList = new ArrayList<>();
                    for (String city : cityArray) {
                        cityList.add(city.trim());
                    }
                    addressMap.put(province, cityList);
                }
            }
        }
        return addressMap;
    }
    /**
     * 初始化省市级菜单栏
     * @param provinceComboBox 省级的菜单
     * @param cityComboBox 市级的菜单
     */
    public static void initAddressComboBox(ComboBox<String> provinceComboBox, ComboBox<String> cityComboBox) throws IOException {
        Map<String, List<String>> addressMap = initAddressMap();
        
        provinceComboBox.setItems(FXCollections.observableArrayList(addressMap.keySet()));
        provinceComboBox.getSelectionModel().selectedItemProperty().addListener(((a, b, newValue) -> {
            if(newValue != null){
                List<String> cities = addressMap.get(newValue);
                cityComboBox.setItems(FXCollections.observableArrayList(cities));
                cityComboBox.setValue(null);
            }
        }));
    }
    
}
